import { addLayer, registerMapLegend, type LineStyle, type SymbolStyle } from '@/map'
import { SegmentLayer, SegmentMidPointLayer } from '../util/segment'
import type { WaypointSegmentItem } from '../util/waypoint-segment'
import { atsRouteSegmentIndex } from './atsroute-index'
import type { ATSRoute } from './types'

const atsRouteStyle: LineStyle = {
  // lineColor: '#C1D5D0',
  lineColor: '#52c41a',
  lineWidth: 0.7,
  lineOpacity: 1.0
}

const atsRouteNameStyle: SymbolStyle = {
  color: '#52c41a',
  textOpacity: 0.8,
  fontScale: 0.8,
  textOffset: [0, 0],
  textJustify: 'center'
}

export let atsRouteLayer: SegmentLayer
export let atsRouteNameLayer: SegmentMidPointLayer<WaypointSegmentItem<ATSRoute>>

function initATSRouteLayer() {
  atsRouteLayer = new SegmentLayer({
    id: 'Entity:ATSRoute',
    name: '航路',
    style: atsRouteStyle,
    segment: atsRouteSegmentIndex.segments(),
    minZoom: 4.5,
    visible: true
  })
  addLayer(atsRouteLayer)
  atsRouteNameLayer = new SegmentMidPointLayer({
    id: 'Entity:ATSRoute:Name',
    name: '航路名称',
    style: atsRouteNameStyle,
    data: atsRouteSegmentIndex.segments(),
    getText: (s) => {
      const lst = s.data
      if (!lst || lst.length === 0) {
        return ''
      }
      let ret: string | null = null
      for (const r of lst) {
        if (!ret) {
          ret = r.id
        } else {
          ret = ret + '\n' + r.id
        }
      }
      return ret as string
    },
    minZoom: 4.5,
    visible: false
  })
  addLayer(atsRouteNameLayer)
}

function initATSRouteLayerLegend() {
  registerMapLegend({
    name: '航路',
    visible() {
      return atsRouteLayer.visible
    },
    setVisible(ok) {
      atsRouteLayer.visible = ok
      if (!ok) {
        atsRouteNameLayer.visible = false
      }
    }
  })
  registerMapLegend({
    name: '航路名称',
    visible() {
      return atsRouteNameLayer.visible
    },
    setVisible(ok) {
      atsRouteNameLayer.visible = ok
      if (ok) {
        atsRouteLayer.visible = ok
      }
    }
  })
}

export function initMap() {
  initATSRouteLayer()
  initATSRouteLayerLegend()
}
